package com.mojo.elastic.controller;

import com.mojo.elastic.pojo.Bank;
import com.mojo.response.ResultListVO;
import com.mojo.response.ResultVO;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * 精确查询
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
@RestController
public class TermSearchController {
    @Resource
    private ElasticsearchOperations elasticsearchOperations;

    @GetMapping("/term")
    public ResultListVO<Bank> termSearch() {
        // 静态方法创建搜索查询对象
        //TermQueryBuilder termQuery = QueryBuilders.termQuery("firstname", "amber");
        TermsQueryBuilder termQuery = QueryBuilders.termsQuery("firstname", "amber", "Winnie");
        // 原生搜索查询builder
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(termQuery);
        // 原生搜索查询
        NativeSearchQuery nsq = builder.build();
        SearchHits<Bank> hits = elasticsearchOperations.search(nsq, Bank.class);
        ArrayList<Bank> list = new ArrayList<>(Math.toIntExact(hits.getTotalHits()));
        for (SearchHit<Bank> hit : hits) {
            list.add(hit.getContent());
        }
        return new ResultListVO<>(list);
    }
}
